﻿// See https://aka.ms/new-console-template for more information
//Console.WriteLine("Hello, World!");

using Plugin.Common;
using Plugin.Host;
using System.Reflection;
using System.Runtime.Loader;

const bool UseCollectibleContexts = false;
const string capitalizer = @"E:\net7\CSharpFundamental\" +
    @"Capitalizer\bin\Debug\net6.0\Capitalizer.dll";
Console.WriteLine(TransformText("big apple", capitalizer));
Console.WriteLine("*******************");

const string pluralizer = @"E:\net7\CSharpFundamental\Pluralizer\bin\Debug\net6.0\Pluralizer.dll";
Console.WriteLine(TransformText("big apple", pluralizer));
Console.WriteLine();
foreach (var context in AssemblyLoadContext.All)
{
    Console.WriteLine($"Context:{context.GetType().Name} {context.Name}");
    foreach (var assembly in context.Assemblies)
    {
        Console.WriteLine($"  Assembly:{assembly.FullName}");
    }
}

static string TransformText(string text, string pluginPath)
{
    var alc = new PluginLoadContext(pluginPath, UseCollectibleContexts);
    try
    {
        Assembly assem = alc.LoadFromAssemblyPath(pluginPath);

        // Locate the type in the assembly that implements ITextPlugin:
        Type pluginType = assem.ExportedTypes.Single(t => typeof(ITextPlugin).IsAssignableFrom(t));

        // Instante the ITextPlugin implementation:
        var plugin = (ITextPlugin)Activator.CreateInstance(pluginType)!;

        if (plugin != null)
            // Call the TransformText method
            return plugin.TransformText(text);

        return "";
    }
    finally
    {
        if (UseCollectibleContexts) alc.Unload(); // unload the ALC
    }
}